<template>
  <div class="sop-generation">
    <el-card>
      <template #header>
        <h2>SOP生成</h2>
      </template>

      <el-form :model="form" label-width="100px">
        <el-form-item label="SOP主题">
          <el-input
            v-model="form.topic"
            placeholder="请输入SOP主题，例如：新员工入职流程"
            :disabled="loading"
          />
        </el-form-item>

        <el-form-item label="输出格式">
          <el-radio-group v-model="form.format" :disabled="loading">
            <el-radio label="pdf">PDF</el-radio>
            <el-radio label="markdown">Markdown</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleGenerate"
            :loading="loading"
            :disabled="!form.topic.trim()"
          >
            生成SOP
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-divider v-if="result" />

      <div v-if="result" class="result-section">
        <el-alert
          v-if="!result.success || !result.hasKnowledge"
          title="暂无相关知识"
          type="warning"
          :closable="false"
          show-icon
          style="margin-bottom: 20px"
        >
          知识库中暂时没有关于"{{ form.topic }}"的相关内容，无法生成SOP文档。请先上传相关文档到知识库。
        </el-alert>

        <div v-else-if="result.success && result.hasKnowledge">
          <el-alert
            title="SOP生成成功"
            type="success"
            :closable="false"
            show-icon
            style="margin-bottom: 20px"
          >
            SOP文档已生成，{{ form.format === 'markdown' ? '可以预览内容并' : '' }}点击下方按钮下载。
          </el-alert>

          <div v-if="form.format === 'markdown' && result.content" class="markdown-preview">
            <h3>预览：</h3>
            <div class="markdown-content" v-html="renderedMarkdown"></div>
          </div>

          <el-button 
            type="success" 
            @click="handleDownload"
            :icon="Download"
          >
            下载{{ form.format === 'pdf' ? 'PDF' : 'Markdown' }}文件
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import { marked } from 'marked'
import { generateSop, downloadSop } from '../api/sop'
import { userStore } from '../store/user'

const form = reactive({
  topic: '',
  format: 'pdf'
})

const loading = ref(false)
const result = ref(null)
const downloadBlob = ref(null)

// 配置marked选项
marked.setOptions({
  breaks: true,
  gfm: true
})

// 计算渲染后的HTML
const renderedMarkdown = computed(() => {
  if (result.value?.content) {
    return marked(result.value.content)
  }
  return ''
})

const handleGenerate = async () => {
  if (!form.topic.trim()) {
    ElMessage.warning('请输入SOP主题')
    return
  }

  loading.value = true
  result.value = null
  downloadBlob.value = null

  try {
    const response = await generateSop(form.topic, form.format, userStore.getCurrentUserId())
    
    // 统一处理JSON响应
    result.value = response
    if (response.success && response.hasKnowledge) {
      ElMessage.success('SOP生成成功')
    } else if (response.success === false) {
      ElMessage.warning(response.message || '暂无相关知识')
    } else {
      ElMessage.warning('暂无相关知识')
    }
  } catch (error) {
    ElMessage.error('生成SOP失败：' + (error.message || '未知错误'))
    console.error('生成SOP失败:', error)
  } finally {
    loading.value = false
  }
}

const handleDownload = async () => {
  if (!form.topic.trim()) {
    ElMessage.warning('请输入SOP主题')
    return
  }

  try {
    ElMessage.info('正在准备下载...')
    const blob = await downloadSop(form.topic, form.format)
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    const extension = form.format === 'pdf' ? 'pdf' : 'md'
    link.download = `${form.topic}_SOP.${extension}`
    
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('下载成功')
  } catch (error) {
    ElMessage.error('下载失败：' + (error.message || '未知错误'))
    console.error('下载失败:', error)
  }
}

const handleReset = () => {
  form.topic = ''
  form.format = 'pdf'
  result.value = null
  downloadBlob.value = null
}
</script>

<style scoped>
.sop-generation {
  max-width: 1000px;
  margin: 0 auto;
}

.result-section {
  margin-top: 24px;
}

.markdown-preview {
  margin-bottom: 24px;
}

.markdown-preview h3 {
  margin-bottom: 12px;
  color: #262626;
  font-size: 16px;
  font-weight: 500;
}

.markdown-content {
  background: linear-gradient(135deg, #f6f8fb 0%, #f0f2f5 100%);
  padding: 24px;
  border-radius: 8px;
  max-height: 500px;
  overflow-y: auto;
  border-left: 4px solid #52c41a;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  line-height: 1.8;
  color: #262626;
  font-size: 14px;
}

/* Markdown渲染样式 */
.markdown-content h1 {
  font-size: 24px;
  font-weight: bold;
  margin: 20px 0 16px 0;
  padding-bottom: 8px;
  border-bottom: 2px solid #e8e8e8;
  color: #262626;
}

.markdown-content h2 {
  font-size: 20px;
  font-weight: bold;
  margin: 18px 0 14px 0;
  color: #262626;
}

.markdown-content h3 {
  font-size: 16px;
  font-weight: bold;
  margin: 16px 0 12px 0;
  color: #262626;
}

.markdown-content h4, .markdown-content h5, .markdown-content h6 {
  font-size: 14px;
  font-weight: bold;
  margin: 14px 0 10px 0;
  color: #262626;
}

.markdown-content p {
  margin: 12px 0;
  line-height: 1.8;
}

.markdown-content ul, .markdown-content ol {
  margin: 12px 0;
  padding-left: 24px;
}

.markdown-content li {
  margin: 6px 0;
  line-height: 1.6;
}

.markdown-content strong {
  font-weight: bold;
  color: #000;
}

.markdown-content em {
  font-style: italic;
}

.markdown-content code {
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
}

.markdown-content pre {
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 16px 0;
}

.markdown-content pre code {
  background-color: transparent;
  padding: 0;
}

.markdown-content blockquote {
  border-left: 4px solid #ddd;
  padding-left: 16px;
  margin: 16px 0;
  color: #666;
  font-style: italic;
}

.markdown-content hr {
  border: none;
  border-top: 1px solid #e8e8e8;
  margin: 24px 0;
}

.markdown-content table {
  border-collapse: collapse;
  width: 100%;
  margin: 16px 0;
}

.markdown-content th, .markdown-content td {
  border: 1px solid #ddd;
  padding: 8px 12px;
  text-align: left;
}

.markdown-content th {
  background-color: #f5f5f5;
  font-weight: bold;
}
</style>
